/*
The MIT License (MIT)

Copyright (c) 2013
David Scruton
Gareth Jones
Jamiel Mendoza
Connor McNamara


Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 
*/


package com.example.parseproject2;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.parse.FindCallback;
import com.parse.LogInCallback;
import com.parse.Parse;
import com.parse.ParseACL;
import com.parse.ParseAnalytics;
import com.parse.ParseException;
import com.parse.ParseInstallation;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.PushService;
import com.parse.SignUpCallback;

public class MainActivity extends Activity {
	/** Called when the activity is first created. */
	
	List<String> tasks = new ArrayList<String>();
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		final ListView list = (ListView) findViewById(R.id.listView1);
		list.setClickable(true);
 	    final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, tasks);
 	    list.setOnItemClickListener(new AdapterView.OnItemClickListener() 
 	    {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) 
			{
				Log.v("Click", arg0.getChildAt(arg2).toString());
				// TODO Auto-generated method stub
				
			}
		});
 	
 	   
		Parse.initialize(this, "sl4QNwawrkUoyP4WMNblv9sq7iTU0XkRikatAAl6", "DJbDNDvlvGwd2h3Rgz8RO830g55mY7oY0pavpubn");
		
		ParseInstallation.getCurrentInstallation().saveInBackground();
		PushService.subscribe(this, "Giants", MainActivity.class);
		
		//
		
		ParseUser currentUser = ParseUser.getCurrentUser();
		if (currentUser != null) 
		{
		  // do stuff with the user
		} 
		else 
		{
		  // show the signup or login screen
			Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
			Account[] accounts = AccountManager.get(this).getAccounts();
			for (Account account : accounts) 
			{
			    if (emailPattern.matcher(account.name).matches()) 
			    {
			        String possibleEmail = account.name;
			        if(possibleEmail.contains("googlemail.com") || possibleEmail.contains("gmail.com"))
			        {
			        	
			        	ParseUser user = new ParseUser();
			        	user.setEmail(possibleEmail);
			        	user.setPassword(possibleEmail);
			        	user.setUsername(possibleEmail);
			        	user.signUpInBackground(new SignUpCallback() 
			        	{
			        		public void done(ParseException e)
			        		{
			        			if(e == null)
			        			{
			        				// good
			        			}
			        			else
			        			{
			        				//bad
			        			}
			        		}
							
							
						});
			        	
			        	//login
			        	ParseUser.logInInBackground("Jerry", "showmethemoney", new LogInCallback() 
			        	{
			        		  public void done(ParseUser user, ParseException e)
			        		  {
			        		    if (user != null) 
			        		    {
			        		      // Hooray! The user is logged in.
			        		    } 
			        		    else 
			        		    {
			        		      // Signup failed. Look at the ParseException to see what happened.
			        		    }
			        		  }
			        	});
			        	//
			        }
			        
			    }
			}
		}
		
		//
		final Handler handler = new Handler();
		Timer timer = new Timer();
		    TimerTask doAsynchronousTask = new TimerTask()
		    {       
		        @Override
		        public void run()
		        {
		            handler.post(new Runnable()
		            {
		                @SuppressLint("NewApi")
						public void run()
		                {
		                   try
		                   {
			                        //check the takslist
			                	   ParseQuery<ParseObject> query = ParseQuery.getQuery("TaskList");
			                	   query.whereEqualTo("Recipient", ParseUser.getCurrentUser().get("username"));
			                	   query.whereEqualTo("Viewed", false);
			                	   query.findInBackground(new FindCallback<ParseObject>() 
			                		{
			                		    public void done(List<ParseObject> TaskList, ParseException e) 
			                		    {
			                		        if (e == null) 
			                		        {
			                		            Log.v("Task Amount", Integer.toString(TaskList.size()));
			                		            
			                		            for(int i = 0; i<TaskList.size(); i++)
			                		            {
			                		            	final ParseObject current = TaskList.get(i);
			                		            	int id = (Integer)TaskList.get(i).getNumber("TaskID");
			                		            	
			     			                	   ParseQuery<ParseObject> query2 = ParseQuery.getQuery("Tasks");
			    			                	   query2.whereEqualTo("TaskID", id);
			    			   
			    			                	   
			    			                	   query2.findInBackground(new FindCallback<ParseObject>() 
			    			                		{
			    			                		    public void done(List<ParseObject> Tasks, ParseException f) 
			    			                		    {
			    			                		    	 if (f == null) 
			    			                		    	 {
			    			                		    		 
			    			                		    		 list.setClickable(false);
			    			                		    		 Log.v("Task Name", Tasks.get(0).getString("Description"));
			    			                		    		 tasks.add(Tasks.get(0).getString("Description"));
			    			                		    		 list.setClickable(true);
			    			                		    		 
			    			                		    		// current.put("Viewed", true); 		    	
			    			                		    		 //current.saveInBackground();
			    			                		    	 }
			    			                		    	 else
			    			                		    	 {
			    			                		    		 
			    			                		    	 }
			    			                		    }
			    			                		});
			                		            }
			                		        } 
			                		        else 
			                		        {
			                		            Log.d("score", "Error: " + e.getMessage());
			                		        }
			                		    }
			                		});
			                	   
			                	   //update list
			                	   //arrayAdapter.clear();
			                	  // arrayAdapter.addAll(tasks);

			                	   list.setClickable(false);
			                	   list.setAdapter(arrayAdapter);
			                	   list.setClickable(true);
			                	   
	                	   
		                       }
		                 catch (Exception e)
		                 {
		                        // TODO Auto-generated catch block
		                 }
		                   
		                }
		            });
		        }
		    };
		    timer.schedule(doAsynchronousTask, 0, 10000); 
		//
		//ParseUser.enableAutomaticUser();
		ParseACL defaultACL = new ParseACL();
	    
		// If you would like all objects to be private by default, remove this line.
		defaultACL.setPublicReadAccess(true);
		
		ParseACL.setDefaultACL(defaultACL, true);
		
		ParseObject testObject = new ParseObject("TestObject");
		testObject.put("foo", "bar");
		testObject.saveInBackground();
		
		
		ParseAnalytics.trackAppOpened(getIntent());
	}
}
